package com.prdiot.poetry.service;

import com.prdiot.poetry.dao.PoemsRepository;
import com.prdiot.poetry.domains.Poems;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class PoemsService {

    private static final String regex = "<p>(.*?)</p>";
    private static final String regexRel = "<div>(.*?)</div>";

    @Autowired
    PoemsRepository poemsRepository;

    @Autowired
    TagsService tagsService;

    //随机50条推送至百度
    public List<Poems> getRandPoetryToBaidu() {
        return poemsRepository.getRandPoetryToBaidu();
    }

    //随机获取诗词列表
    public List<Poems> getRandPoetry() {
        List<Poems> poemsList = poemsRepository.getRandPoetry();
        return attachTag(poemsList);
    }
    public List<Poems> attachTag(List<Poems> poemsList){
        if (poemsList != null && poemsList.size()>0){
            for (Poems poem: poemsList) {
                attachTagToPoems(poem);
            }
        }
        return poemsList;
    }
    private Poems attachTagToPoems(Poems poem){
        Map<String, String> tagsMap = tagsService.getTagsMap();
        String[] tagNames = poem.getTag().split(",");
        Map<String, String> poemTags = new HashMap<>();
        for (String tagName: tagNames) {
            if (tagsMap.containsKey(tagName.trim())){
                poemTags.put(tagsMap.get(tagName.trim()),tagName.trim());
            }
        }
        poem.setTags(poemTags);
        return poem;
    }

    //获取诗文译注解释数据
    public Map<String, Object> getPoetryExt(String poemid) {

        Optional<Poems> poemsOptional = poemsRepository.findById(Integer.valueOf(poemid));
        if (poemsOptional.isPresent()) {
            Map<String, Object> map = new HashMap<>();
            Poems poems = poemsOptional.get();
            //原文
            String body = poems.getBody();
            Pattern pBody = Pattern.compile(regex);
            Matcher mBody = pBody.matcher(body);
            List<String> poemBody = new ArrayList<>();
            while (mBody.find()){
                poemBody.add(mBody.group(1));
            }
            map.put("body",poemBody);

            //译
            String trans = poems.getTranslation();
            Pattern pTrans = Pattern.compile(regex);
            Matcher mTrans = pTrans.matcher(trans);
            List<String> poemTrans = new ArrayList<>();
            while (mTrans.find()){
                poemTrans.add(mTrans.group(1));
            }
            map.put("trans",poemTrans.size()==0?null:poemTrans);

            Pattern pTransRel = Pattern.compile(regexRel);
            Matcher mTransRel = pTransRel.matcher(trans);
            String transRel = "";//参考资料
            if (mTransRel.find()){
                transRel = mTransRel.group(1);
            }
            map.put("transRel",transRel);

            //注
            String explanation = poems.getExplanation();
            Pattern pExplanation = Pattern.compile(regex);
            Matcher mExplanation = pExplanation.matcher(explanation);
            List<String> poemExplanation = new ArrayList<>();
            while (mExplanation.find()){
                poemExplanation.add(mExplanation.group(1));
            }
            map.put("expl",poemExplanation.size()==0?null:poemExplanation);

            //注解暂时没有参考资料
//            Pattern pExplanationRel = Pattern.compile(regexRel);
//            Matcher mExplanationRel = pExplanationRel.matcher(explanation);
//            String explanationRel = "";//参考资料
//            if (mExplanationRel.find()){
//                explanationRel = mExplanationRel.group(1);
//            }
//            map.put("explRel",explanationRel);
            //赏
            String shang = poems.getAppreciation();
            map.put("shang",shang);

            return map;

        }
        return null;
    }

    //key id val:name
    private static List<Map<String, String>> DYNASTY_LIST = new ArrayList<>();
    //key name val:id
    private static List<Map<String, String>> DYNASTY_LIST_REVERSE = new ArrayList<>();
    private static volatile boolean DYNASTY_LIST_INIT = false;

    public List<Map<String, String>> getDynastyList(){
        if (!DYNASTY_LIST_INIT){
            initDynastyList();
        }
        return DYNASTY_LIST;
    }
    public List<Map<String, String>> getDynastyListReverse(){
        if (!DYNASTY_LIST_INIT){
            initDynastyList();
        }
        return DYNASTY_LIST_REVERSE;
    }
    private void initDynastyList(){
        //经典单例 双重检测 确保线程安全
        if(!DYNASTY_LIST_INIT) {
            synchronized (PoemsService.class) {
                if (!DYNASTY_LIST_INIT) {
                    List<Map<String, String>> list = poemsRepository.listDynasty();
                    for (Map<String, String> map:list) {
                        Map<String, String> tmp = new HashMap();
                        tmp.put(map.get("dynasty_id").toString(),map.get("dynasty").toString());
                        DYNASTY_LIST.add(tmp);
                        tmp = new HashMap();
                        tmp.put(map.get("dynasty").toString(),map.get("dynasty_id").toString());
                        DYNASTY_LIST_REVERSE.add(tmp);
                    }
                    DYNASTY_LIST_INIT = true;
                }
            }
        }
    }

    public String getDynastyNameById(String dynastryId){
        List<Map<String, String>> list = getDynastyList();
        for (Map<String, String> map:list) {
            if(map.containsKey(dynastryId)){
                return map.get(dynastryId);
            }
        }
        return "";
    }

    public String getDynastyIdByName(String dynastry){
        List<Map<String, String>> list = getDynastyListReverse();
        for (Map<String, String> map:list) {
            if(map.containsKey(dynastry)){
                return map.get(dynastry);
            }
        }
        return "";
    }

    //按照tag查询诗文
    public Page<Poems> searchPoemsByTag(String key, Pageable pageable){
        return poemsRepository.searchPoemsByTag(key, pageable);
    }


    //按照authorId 随机推荐诗文
    public List<Poems> getRandPoetryByAuthorId(String authorId){
        return poemsRepository.getRandPoetryByAuthorId(authorId);
    }
    //按照authorId查询诗文
    public Page<Poems> searchPoemsByAuthorId(String key, Pageable pageable){
        return poemsRepository.searchPoemsByAuthorId(key, pageable);
    }

    //按照dynastyId查询诗文
    public Page<Poems> searchPoemsByDynastyId(String key, Pageable pageable){
        return poemsRepository.searchPoemsByDynastyId(key, pageable);
    }

    //按照type查询诗文
    public Page<Poems> searchPoemsByType(String key, Pageable pageable){
        return poemsRepository.searchPoemsByType(key, pageable);
    }

    //按照code查询诗文
    public Poems searchPoemsByCode(String code){
        Optional<Poems> optionalPoems = poemsRepository.findByCode(code);
        if (optionalPoems.isPresent()){
            return attachTagToPoems(optionalPoems.get());
        }
        return null;
    }

    public List<Poems> findAllPoems(){
        return poemsRepository.findAll();
    }

}
